<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\func\Lib;
use app\common\func\Tools;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

/**
 * 达标设置
 *
 * @icon fa fa-circle-o
 */
class Stardard extends Backend
{

    protected $searchFields = 'title';

    /**
     * Stardard模型对象
     * @var \app\common\model\Stardard
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Stardard;
        $this->view->assign("mainTypeList", $this->model->getMainTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            $this->view->assign("is_admin",$this->auth->isSuperAdmin());
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();

        $query = $this->model;

        if(!$this->auth->isSuperAdmin()){
            $company = $this->auth->getCompany();
            $query->where(["main_type" => 1 ,"main_id" => $company->id]);
        }else{
            $query->where(["main_type" => 0 ,"main_id" => 0]);
        }
        $query->where(["status"=>1]);

        $list = $query->where($where)
            ->order($sort, $order)
            ->paginate($limit);

        foreach ($list as $row) {
            $main = Tools::getMainInfo($row->main_type,$row->main_id);
            $row->main_type = $main['type'];
            $row->main_id = $main['name'];
        }
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    public function add_all(){
        if($this->auth->isSuperAdmin()){
            $this->error("无法使用该功能！");
        }
        $company = $this->auth->getCompany();

        if (false === $this->request->isPost()) {
            $this->view->assign('super', !$this->auth->isSuperAdmin() ? true : false);
            if(!$this->auth->isSuperAdmin()){
                $list = Lib::getPolicyRelationList(1,$this->auth->getCompany()->id);
                $companyIds = Lib::getCompanyProducts(1,$this->auth->getCompany()->id);
                $this->view->assign('ids', implode(",",$companyIds));
                $this->view->assign("list",$list);
                $this->view->assign("is_admin",false);
            }else{
                $this->view->assign("is_admin",true);
            }
            $list = Lib::getStandards($company->pid > 0 ? 1:0,$company->pid);
            $this->view->assign("lists",$list);
            return $this->view->fetch();
        }

        $params = $this->request->post("data/a");

        if(count($params) > 0){
            $info = [];
            foreach ($params as $key => $val){
                $info[] = [
                    "main_type" => 1,
                    "main_id" => $company->id,
                    "title" => $val['title'],
                    "day_limit" => $val['day_limit'],
                    "money" => $val['money'],
                    "reward" => $val['reward'],
                ];
            }

            $result = false;
            Db::startTrans();
            try {
                $result = $this->model->allowField(true)->saveAll($info);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result === false) {
                $this->error(__('No rows were inserted'));
            }
            $this->success();
        }else{
            $this->error("缺少数据！");
        }
    }


    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            $this->view->assign('super', !$this->auth->isSuperAdmin() ? true : false);
            if(!$this->auth->isSuperAdmin()){
                $list = Lib::getPolicyRelationList(1,$this->auth->getCompany()->id);
                $companyIds = Lib::getCompanyProducts(1,$this->auth->getCompany()->id);
                $this->view->assign('ids', implode(",",$companyIds));
                $this->view->assign("list",$list);
                $this->view->assign("is_admin",false);
            }else{
                $this->view->assign("is_admin",true);
            }
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }

            if(!$this->auth->isSuperAdmin()){
                $company = $this->auth->getCompany();
                if(!$company){
                    $this->error(__('未绑定机构，请联系上级绑定！'));
                }
                $params['main_type'] = 1;
                $params['main_id'] = $company->id;
            }

            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $policyList = Lib::getPolicyBySetting("standard",$item->id);

                if(count($policyList) > 0){
                    $this->error("已绑定政策，不可删除！");
                }
                $item->status = 2;
                if($item->save()){
                    $count += 1;
                }
//                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

    public function ajax(){
        $policyId = $this->request->post("id");
        $policy = Lib::getPolicy($policyId);
        $profit = Lib::getProfitById($policy->profit_id);
        $this->success("","",["standard"=>Lib::getStandardByIds($policy->stardard_id),"product_id" => $profit->product_id,"profit_id" => $profit->id]);
    }

}
